package com.ssy.lingxi.platform.template.service.serviceimpl.mobile;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.template.service.entity.adorn.AppAdorn;
import com.ssy.lingxi.platform.template.service.entity.adorn.PageTemplate;
import com.ssy.lingxi.platform.template.service.model.bo.SelfMemberBO;
import com.ssy.lingxi.platform.template.service.model.dto.common.IdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.common.MemberIdAndRoleIdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.mobile.ChannelMemberCategoryMobileDTO;
import com.ssy.lingxi.platform.template.service.model.vo.mobile.MobileCategoryVO;
import com.ssy.lingxi.platform.template.service.repository.AppAdornRepository;
import com.ssy.lingxi.platform.template.service.repository.PageTemplateRepository;
import com.ssy.lingxi.platform.template.service.service.mobile.CategoryMobileService;
import com.ssy.lingxi.search.api.feign.ITemplateChannelFeign;
import com.ssy.lingxi.search.api.feign.ITemplateFeign;
import com.ssy.lingxi.search.api.model.response.CategoryResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fhj
 * @version 2.0.0
 * mobile - 品类 - 业务实现层
 * @date 2021/09/02
 */
@Slf4j
@Service
public class CategoryMobileServiceImpl implements CategoryMobileService {

    @Resource
    private PageTemplateRepository pageTemplateRepository;
    @Resource
    private AppAdornRepository appAdornRepository;
    @Resource
    private ITemplateFeign templateFeign;
    @Resource
    private ITemplateChannelFeign templateChannelFeign;

    @Override
    @ApiOperation(value = "APP企业商城首页（B端、C端）平台品类")
    public Wrapper<List<MobileCategoryVO>> enterpriseCategory(IdDTO dto) {
        //获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getId()).orElse(null);
        if (pageTemplate == null) {
            return Wrapper.fail(ResponseCode.PT_NO_MATCHING_TEMPLATE_FOUND);
        }

        //获取模板对应的品类导航装修内容里的所有一级平台品类
        List<Long> categoryIdList = new ArrayList<>();
        //App企业商城只能由平台后台管理员能装修，即memberId=1，RoleId=1
        AppAdorn appAdorn = appAdornRepository.findByTemplateIdAndMemberIdAndRoleId(dto.getId(), 1L, 1L);
        if (appAdorn != null && CollectionUtil.isNotEmpty(appAdorn.getCategoryAdornContent())) {
            JSONObject categoryAdornContent = JSONUtil.parseObj(appAdorn.getCategoryAdornContent());
            JSONArray category = categoryAdornContent.getJSONArray("category");
            for (Object value : category) {
                JSONObject o = (JSONObject) value;
                Boolean visible = o.getBool("visible");
                if (visible != null && visible) {
                    categoryIdList.add(o.getLong("id"));
                }
            }
        }

        //调用搜索服务 -> 获取所有一级平台品类
        Wrapper<List<CategoryResponse>> wrapper = templateFeign.getFirstCategoryListByMemberId(pageTemplate.getShopId(), null, null);
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(wrapper.getData())) {
            log.info("获取不到一级平台品类（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        //组装
        return Wrapper.success(
                wrapper.getData().stream().map(c -> {
                    MobileCategoryVO vo = new MobileCategoryVO();
                    vo.setId(c.getId());
                    vo.setName(c.getName());
                    vo.setStatus(categoryIdList.contains(c.getId()));
                    return vo;
                }).collect(Collectors.toList())
        );
    }

    @Override
    @ApiOperation(value = "校验平台品类是否存在于品类导航页")
    public Wrapper<Boolean> checkCategory(Long templateId, Long categoryId) {
        //校验
        if (templateId == null || categoryId == null) {
            return Wrapper.fail(ResponseCode.PT_PARAMETER_CHECK_EXCEPTION);
        }
        //获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(templateId).orElse(null);
        if (pageTemplate == null) {
            return Wrapper.fail(ResponseCode.PT_NO_MATCHING_TEMPLATE_FOUND);
        }

        //获取模板对应的品类导航装修内容里的所有一级平台品类，然后跟参数平台品类ID进行匹配
        AppAdorn appAdorn = appAdornRepository.findByTemplateId(templateId);
        if (appAdorn != null && CollectionUtil.isNotEmpty(appAdorn.getCategoryAdornContent())) {
            JSONObject categoryAdornContent = JSONUtil.parseObj(appAdorn.getCategoryAdornContent());
            JSONArray category = categoryAdornContent.getJSONArray("category");
            for (Object value : category) {
                JSONObject o = (JSONObject) value;
                Boolean visible = o.getBool("visible");
                if (visible != null && visible) {
                    if (categoryId.equals(o.getLong("id"))) {
                        return Wrapper.success(Boolean.TRUE);
                    }
                }
            }
        }

        return Wrapper.success(Boolean.FALSE);
    }

    @Override
    @ApiOperation(value = "APP渠道商城首页会员品类")
    public Wrapper<List<MobileCategoryVO>> channelMemberCategory(ChannelMemberCategoryMobileDTO dto, UserLoginCacheDTO user) {
        //获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getId()).orElse(null);
        if (pageTemplate == null) {
            return Wrapper.fail(ResponseCode.PT_NO_MATCHING_TEMPLATE_FOUND);
        }

        //获取模板对应的品类导航装修内容里的所有一级会员品类
        List<Long> memberCategoryIdList = new ArrayList<>();
        AppAdorn appAdorn = appAdornRepository.findByTemplateIdAndMemberIdAndRoleId(dto.getId(), dto.getMemberId(), dto.getRoleId());
        if (appAdorn != null && CollectionUtil.isNotEmpty(appAdorn.getCategoryAdornContent())) {
            JSONObject categoryAdornContent = JSONUtil.parseObj(appAdorn.getCategoryAdornContent());
            JSONArray category = categoryAdornContent.getJSONArray("category");
            for (Object value : category) {
                JSONObject o = (JSONObject) value;
                Boolean visible = o.getBool("visible");
                if (visible != null && visible) {
                    memberCategoryIdList.add(o.getLong("id"));
                }
            }
        }

        //调用搜索服务 -> 获取所有一级平台品类
        Wrapper<List<CategoryResponse>> wrapper = templateChannelFeign.getFirstCategoryListByMemberId(pageTemplate.getShopId(), dto.getMemberId());
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(wrapper.getData())) {
            log.info("获取不到一级平台品类（检查平台后台是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        //组装
        return Wrapper.success(
                wrapper.getData().stream().map(c -> {
                    MobileCategoryVO vo = new MobileCategoryVO();
                    vo.setId(c.getId());
                    vo.setName(c.getName());
                    vo.setStatus(memberCategoryIdList.contains(c.getId()));
                    return vo;
                }).collect(Collectors.toList())
        );
    }

    @Override
    public Wrapper<List<MobileCategoryVO>> selfMemberCategory(IdDTO dto, MemberIdAndRoleIdDTO midAndRId) {
        //获取模板
        PageTemplate pageTemplate = pageTemplateRepository.findById(dto.getId()).orElse(null);
        if (pageTemplate == null) {
            return Wrapper.fail(ResponseCode.PT_NO_MATCHING_TEMPLATE_FOUND);
        }

        //获取模板对应的品类导航装修内容里的所有一级商家品类
        List<Long> categoryIdList = new ArrayList<>();
        AppAdorn appAdorn = appAdornRepository.findByTemplateIdAndMemberIdAndRoleId(dto.getId(), midAndRId.getMemberId(), midAndRId.getRoleId());
        if (appAdorn != null && CollectionUtil.isNotEmpty(appAdorn.getCategoryAdornContent())) {
            JSONObject categoryAdornContent = JSONUtil.parseObj(appAdorn.getCategoryAdornContent());
            JSONArray category = categoryAdornContent.getJSONArray("category");
            for (Object value : category) {
                JSONObject o = (JSONObject) value;
                Boolean visible = o.getBool("visible");
                if (visible != null && visible) {
                    categoryIdList.add(o.getLong("id"));
                }
            }
        }
        List<SelfMemberBO> useSelfTemplate = pageTemplate.getUseSelfTemplate();
        //获取自营商城id
        if (CollectionUtil.isNotEmpty(useSelfTemplate)) {
            SelfMemberBO selfMemberBO = useSelfTemplate.stream().filter(b ->
                    b.getMemberId().equals(midAndRId.getMemberId()) && b.getRoleId().equals(midAndRId.getRoleId())
            ).collect(Collectors.toList()).get(0);
            if (selfMemberBO != null) {
                pageTemplate.setShopId(selfMemberBO.getShopId());
            }
        }
        //调用搜索服务 -> 获取所有一级商家品类
        Wrapper<List<CategoryResponse>> wrapper = templateFeign.getFirstCategoryListByMemberId(pageTemplate.getShopId(), midAndRId.getMemberId(), midAndRId.getRoleId());
        if (wrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.info("请求搜索服务失败:{}", wrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_SEARCH_ERROR);
        }
        if (CollectionUtil.isEmpty(wrapper.getData())) {
            log.info("获取不到一级商家品类（检查该商家是否添加了品类）");
            return Wrapper.success(new ArrayList<>());
        }

        //组装
        return Wrapper.success(
                wrapper.getData().stream().map(c -> {
                    MobileCategoryVO vo = new MobileCategoryVO();
                    vo.setId(c.getId());
                    vo.setName(c.getName());
                    vo.setStatus(categoryIdList.contains(c.getId()));
                    return vo;
                }).collect(Collectors.toList())
        );
    }
}
